<script setup lang="ts">
import * as monaco from "monaco-editor";
import {
  onMounted,
  ref,
  toRaw,
  withDefaults,
  defineProps,
  watch, toRef
} from 'vue'

const codeEditorRef = ref();
const codeEditor = ref();

//定义子组件中接收的属性类型
interface Props {
  //代码
  value: string;
  //语言
  language: string;
  //回调函数
  handleChange: (v: string) => void;
}

//定义接收的属性默认值
const props = withDefaults(defineProps<Props>(), {
  value: () => "",
  language: "java",
  handleChange: (v: string) => {
    console.log(v);
  },
});
//监听props的language属性
watch(() => props.language, (newLang) => {
  if (codeEditor.value) {
    // 获取当前代码编辑器的模型
    const model = toRaw(codeEditor.value).getModel();
    if (model) {
      // 使用 monaco.editor.setModelLanguage 方法修改模型的语言
      monaco.editor.setModelLanguage(model, props.language);
    }
  }
});

//监听props的value属性
watch(toRef(props, 'value'), (newVal) => {
  if (codeEditor.value) {
    const currentValue = toRaw(codeEditor.value).getValue();
    if (currentValue !== newVal) {
      toRaw(codeEditor.value).setValue(newVal);
    }
  }
});

onMounted(() => {
  console.log("代码："+props.value)
  if (!codeEditorRef.value) {
    return;
  }
  // 创建代码编辑器并将它挂载到一个DOM元素上
  //返回Monaco编辑器实例，可以通过操作这个实例来操作编辑器
  codeEditor.value = monaco.editor.create(codeEditorRef.value, {
    value: props.value,
    language: props.language,
    automaticLayout: true,
    colorDecorators: true,
    folding: true,  // 启用代码折叠
    formatOnPaste: true,  // 粘贴时自动格式化
    matchBrackets: "always",
    minimap: {
      enabled: false,
    },
    readOnly: false,
    theme: "vs-dark",
  });
  // 编辑 监听内容变化
  codeEditor.value.onDidChangeModelContent(() => {
    props.handleChange(toRaw(codeEditor.value).getValue());
  });
});
</script>

<template>
  <div
    id="code-editor"
    ref="codeEditorRef"
    style="min-height: 400px; height: 75vh"
  />
</template>

<style scoped></style>
